package com.example.demo.Controller.Upload;

import com.example.demo.Bean.R;
import com.example.demo.Component.FileUtil;
import com.example.demo.Component.WordToHtml;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

@RestController
@Slf4j
@Tag(name = "文件上传接口")
public class UploadController {
    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R upload(@RequestPart("file") MultipartFile file) throws IOException {
        log.info(file.getName());
        log.info(Objects.requireNonNull(file.getOriginalFilename()).split("\\.")[0]);
        file.transferTo(new File("C:/Users/Administrator/Desktop/thesis/"+file.getOriginalFilename()));
        return R.ok().put("url","http://localhost:8080/file/"+file.getOriginalFilename());
    }
    @GetMapping(value = "/docs")
    public R doc(@RequestParam String url) throws UnsupportedEncodingException {
        String replacedString = url.replace("http://localhost:8080/file/", "C:/Users/Administrator/Desktop/thesis/");
        File file=new File(replacedString);
        String fileName = Objects.requireNonNull(file.getName().split("\\.")[0]) + ".html";
        if(WordToHtml.Transform(file.getAbsolutePath(),fileName)){
            FileUtil.convertToGBKWithMeta("C:/Users/Administrator/Desktop/thesis/"+fileName);
            return R.ok().put("url","http://localhost:8080/file/"+fileName);
        }else{
            return R.error();
        }
    }
}
